package com.carey.blog.event.baidu.zone;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.json.JSONObject;

import com.carey.blog.event.EventTypes;
import com.carey.blog.event.tencent.microblog.TencentMicroblogSender;
import com.carey.blog.framework.latke.event.AbstractEventListener;
import com.carey.blog.framework.latke.event.Event;
import com.carey.blog.framework.latke.event.EventException;
import com.carey.blog.framework.latke.event.EventManager;
import com.carey.blog.libs.baidu.BDHttpClient;
import com.carey.blog.model.Article;
import com.carey.blog.model.Preference;
import com.carey.blog.util.Preferences;

/**
 * This listener is responsible for sending article publish information to
 * author's <a href="http://hi.baidu.com">Baidu Zone</a>.
 * 
 */
public final class BaiduZoneSender extends AbstractEventListener<JSONObject> {
	private static final String ARTICLE_TITLE = "article_title";
	private static final String ARTICLE_CONTENT = "article_content";
	private static final String ARTICLE_CATEGORY = "article_category";

	/**
	 * Logger.
	 */
	private static final Logger LOGGER = Logger.getLogger(BaiduZoneSender.class
			.getName());
	/**
	 * Preference utilities.
	 */
	private Preferences preferenceUtils = Preferences.getInstance();

	/**
	 * Constructs a {@link TencentMicroblogSender} object with the specified
	 * event manager.
	 * 
	 * @param eventManager
	 *            the specified event manager
	 */
	public BaiduZoneSender(final EventManager eventManager) {
		super(eventManager);
	}

	@Override
	public void action(final Event<JSONObject> event) throws EventException {
		final JSONObject preference = preferenceUtils.getPreference();
		if (null == preference) {
			throw new EventException("Not found preference");
		}

		final boolean enabled = preference
				.optBoolean(Preference.ENABLE_POST_TO_BAIDU_ZONE);
		if (!enabled) {
			return;
		}

		final JSONObject data = event.getData();
		LOGGER.log(
				Level.FINER,
				"Processing an event[type={0}, data={1}] in listener[className={2}]",
				new Object[] { event.getType(), data,
						BaiduZoneSender.class.getName() });
		try {
			final JSONObject article = data.getJSONObject(Article.ARTICLE);

			final Map<String, String> ret = generateArticleInfo(preference,
					article);

			final String baiduZoneUsername = preference
					.getString(Preference.BAIDU_ZONE_USERNAME);
			final String baiduZonePassword = preference
					.getString(Preference.BAIDU_ZONE_PASSWORD);

			new BDHttpClient(baiduZoneUsername, baiduZonePassword, "gb2312")
					.publishBlog(ret.get(ARTICLE_TITLE),
							ret.get(ARTICLE_CONTENT), ret.get(ARTICLE_CATEGORY));

			LOGGER.log(Level.INFO,
					"Success sends article to Baidu Zone<{0}> : [{1}]--{2}",
					new Object[] { baiduZoneUsername,
							ret.get(ARTICLE_CATEGORY), ret.get(ARTICLE_TITLE) });
		} catch (final Exception e) {
			LOGGER.log(Level.SEVERE, "Sends article to Baidu Zone error: {0}",
					e.getMessage());
		}
	}

	/**
	 * Gets the event type {@linkplain EventTypes#ADD_ARTICLE}.
	 * 
	 * @return event type
	 */
	@Override
	public String getEventType() {
		return EventTypes.ADD_ARTICLE;
	}

	/**
	 * generate Article Description .
	 * 
	 * @param article
	 * @return Content
	 */
	private Map<String, String> generateArticleInfo(JSONObject preference,
			JSONObject article) {
		final Map<String, String> ret = new HashMap<String, String>();

		try {
			final String title = article.getString(Article.ARTICLE_TITLE);
			final String content = article.getString(Article.ARTICLE_CONTENT);
			final String permalink = article
					.getString(Article.ARTICLE_PERMALINK);
			final String tagsString = article
					.getString(Article.ARTICLE_TAGS_REF);
			final String[] tagStrings = tagsString.split(",");

			final String blogTitle = preference
					.getString(Preference.BLOG_TITLE);
			final String blogHost = preference.getString(Preference.BLOG_HOST);
			final String blogDomain = blogHost.split(":")[0];

			final StringBuilder descriptionBuilder = new StringBuilder(content);

			// TODO: i18N
			descriptionBuilder.append("<br/><br/>");
			descriptionBuilder
					.append("<div style='font: italic normal normal 11px Verdana'>");
			descriptionBuilder
					.append("本文是使用 <a href='http://carey-blog.googlecode.com//'>");
			descriptionBuilder.append("Carey Blog</a> 从 <a href='http://");
			descriptionBuilder.append(blogHost);
			descriptionBuilder.append("'>");
			descriptionBuilder.append(blogTitle);
			descriptionBuilder.append("</a> 进行同步发布的</div>");
			descriptionBuilder
					.append("<div style='font: italic normal normal 11px Verdana'>");
			descriptionBuilder.append("原文地址：<a href='http://");
			descriptionBuilder.append(blogDomain);
			descriptionBuilder.append(permalink);
			descriptionBuilder.append("'>");
			descriptionBuilder.append("http://");
			descriptionBuilder.append(blogDomain);
			descriptionBuilder.append(permalink);
			descriptionBuilder.append("</a></div>");

			ret.put(ARTICLE_CONTENT, descriptionBuilder.toString());
			ret.put(ARTICLE_CATEGORY, tagStrings[0]);
			ret.put(ARTICLE_TITLE, title);
		} catch (final Exception e) {
			LOGGER.log(Level.SEVERE, e.getMessage(), e);
			throw new RuntimeException(e);
		}

		return ret;
	}
}
